package com.platform.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.platform.common.Result;
import com.platform.dto.PreOrderQo;
import com.platform.entity.*;
import com.platform.exception.CustomException;
import com.platform.mapper.UserOrderMapper;
import com.platform.service.*;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/api/userOrder")
public class UserOrderController {
    @Resource
    private OrderService orderService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private SysUserService userService;
    @Resource
    private UserCartService cartService;
    @Resource
    private OrderProductService orderProductService;
    @Resource
    private ProductService productService;

    public SysUser getUser() {
        String token = request.getHeader("token");
        String username = JWT.decode(token).getAudience().get(0);
        return userService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username));
    }

    @Transactional
    @PostMapping
    public Result<?> save(@RequestBody UserOrder order) {
        order.setUserId(getUser().getId());
        order.setOrderNo(DateUtil.format(new Date(), "yyyyMMddHHmmss") + RandomUtil.randomNumbers(6));
        order.setCreateTime(DateUtil.now());

        String cartsStr = order.getCarts();
        List<UserCart> carts = JSONUtil.toBean(cartsStr, new TypeReference<List<UserCart>>() {
        }, true);
        orderService.save(order);

        for (UserCart cart : carts) {
            Integer count = cart.getCount();
            Long goodsId = cart.getGoodsId();

            // 扣库存
            Product goods = productService.getById(goodsId);
            if(goods.getStore() - cart.getCount() < 0) {
                throw new CustomException("-1", "库存不足");
            }
            goods.setStore(goods.getStore() - cart.getCount());
            goods.setSales(goods.getSales() + cart.getCount());
            productService.updateById(goods);

            OrderProduct orderGoods = new OrderProduct();
            orderGoods.setOrderId(order.getId());
            orderGoods.setGoodsId(goodsId);
            orderGoods.setCount(count);
            orderProductService.save(orderGoods);
        }

        if (order.getType() == 1) {  // 1表示购物车，0表示直接购买
            // 提交订单时清空个人的购物车商品
            cartService.remove(Wrappers.<UserCart>lambdaUpdate().eq(UserCart::getUserId, getUser().getId()));
        }

        return Result.success(order);
    }

    @PutMapping
    public Result<?> update(@RequestBody UserOrder order) {
        orderService.updateById(order);
        return Result.success();
    }

    /**
     * 付款
     * @param id
     * @return
     */
//    @Transactional
//    @PutMapping("/pay/{id}")
    public Result<?> pay(@PathVariable Long id) {
        UserOrder order = orderService.getById(id);
        BigDecimal totalPrice = order.getTotalPrice();

        Long userId = getUser().getId();
        SysUser user = userService.findById(userId);

        if (user.getAccount().compareTo(totalPrice) <= 0) {
            throw new CustomException("-1", "余额不足");
        }

        user.setAccount(user.getAccount().subtract(totalPrice)); // 设置用户余额
        userService.updateById(user);
        order.setState("待发货");
        orderService.updateById(order);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        orderService.removeById(id);
        return Result.success();
    }

    /**
     * 获取订单的确认信息
     *
     * @return
     */
    @PostMapping("/pre")
    public Result<?> pre(@RequestBody PreOrderQo preOrderQo) throws JSONException {
        String cartsStr = preOrderQo.getCarts();
        // 讲前台传来的json字符串转换成 list对象
        List<UserCart> carts = JSONUtil.toBean(cartsStr, new TypeReference<List<UserCart>>() {
        }, true);
        Map<String, Object> all = cartService.findAll(carts);
        return Result.success(all);
    }

    @GetMapping("/{id}")
    public Result<?> findById(@PathVariable Long id) {
        return Result.success(orderService.getById(id));
    }

    @GetMapping
    public Result<?> findAll() {
        List<UserOrder> list = orderService.list();
        return Result.success(list);
    }

    @GetMapping("/page")
    public Result<?> findPage(@RequestParam(required = false, defaultValue = "") String name,
                              @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                              @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        LambdaQueryWrapper<UserOrder> query = Wrappers.<UserOrder>lambdaQuery().orderByDesc(UserOrder::getId);
        if (StrUtil.isNotBlank(name)) {
            query.like(UserOrder::getOrderNo, name);
        }
        IPage<UserOrder> page = orderService.page(new Page<>(pageNum, pageSize), query);
        return Result.success(page);
    }

    /**
     * 前台查询订单列表
     * @param state
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/page/front")
    public Result<?> findPageFront(@RequestParam(required = false, defaultValue = "") String state,
                                   @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                   @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        LambdaQueryWrapper<UserOrder> query = Wrappers.<UserOrder>lambdaQuery().orderByDesc(UserOrder::getId);
        query.eq(UserOrder::getUserId, getUser().getId());
        // 根据状态查询
        if (StrUtil.isNotBlank(state)) {
            query.eq(UserOrder::getState, state);
        }
        IPage<UserOrder> page = orderService.page(new Page<>(pageNum, pageSize), query);

        for (UserOrder order : page.getRecords()) {
            Long orderId = order.getId();
            List<UserCart> carts = orderProductService.findByOrderId(orderId);
            order.setCarts(JSONUtil.toJsonStr(carts));
        }
        return Result.success(page);
    }


    @Resource
    private UserOrderMapper userOrderMapper;

    //修改订单为已评价
    @GetMapping("/ok")
    public Result<?> ok(@RequestParam("orderNo")String orderNo){
        LambdaQueryWrapper<UserOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserOrder::getOrderNo,orderNo);
        UserOrder userOrder = userOrderMapper.selectList(wrapper).get(0);
        userOrder.setState("已完成");
        userOrderMapper.updateById(userOrder);
        return Result.success();
    }

    @GetMapping("orderType")
    public Result<?> orderType(){
        LambdaQueryWrapper<UserOrder> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(UserOrder::getState,"待付款");
        Integer count1 = userOrderMapper.selectCount(wrapper1);

        LambdaQueryWrapper<UserOrder> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(UserOrder::getState,"待收货");
        Integer count2 = userOrderMapper.selectCount(wrapper2);

        LambdaQueryWrapper<UserOrder> wrapper3 = new LambdaQueryWrapper<>();
        wrapper2.eq(UserOrder::getState,"待评价");
        Integer count3 = userOrderMapper.selectCount(wrapper2);

        LambdaQueryWrapper<UserOrder> wrapper4 = new LambdaQueryWrapper<>();
        wrapper4.eq(UserOrder::getState,"已完成");
        Integer count4 = userOrderMapper.selectCount(wrapper4);

//        全部订单
        Integer count5 = userOrderMapper.selectCount(null);

        List<Object> list = new ArrayList<>();


        HashMap<Object, Object> map4 = new HashMap<>();
        map4.put("name","已完成");
        map4.put("value",count4);
        list.add(map4);

        HashMap<Object, Object> map1 = new HashMap<>();
        map1.put("name","待付款");
        map1.put("value",count1);
        list.add(map1);

        HashMap<Object, Object> map2 = new HashMap<>();
        map2.put("name","待收货");
        map2.put("value",count2);
        list.add(map2);

        HashMap<Object, Object> map3 = new HashMap<>();
        map3.put("name","待评价");
        map3.put("value",count3);
        list.add(map3);

        List<String> list2 = com.platform.utils.DateUtil.getDate();
        List<Object> returnMap = new ArrayList<>();
        List<Object> yList = new ArrayList<>();
        for (String str : list2) {
            //要注意顺序
            LambdaQueryWrapper<UserOrder> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper
                    .apply("DATE_FORMAT(create_time, '%Y-%m-%d') = {0}", str)
                    .eq(UserOrder::getState,"已完成");

            //还书列表
            HashMap<Object, Object> map = new HashMap<>();
            map.put("name", str);
            map.put("value", userOrderMapper.selectCount(queryWrapper));
            returnMap.add(map);

            yList.add(userOrderMapper.selectCount(queryWrapper));
        }
        HashMap<Object, Object> map = new HashMap<>();
        map.put("x", list2);
        map.put("y", yList);
        HashMap<Object, Object> result = new HashMap<>();

        result.put("one",list);
        result.put("two",map);
        return Result.success(result);
    }

}
